﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class TrainingsPlacesCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TrainingsPlaces> _list;

        /// <summary>
        /// Список объектов
        /// </summary>
        public List<TrainingsPlaces> TrainingsPlacesList
        {
            get
            {
                return Entities.TrainingsPlaces.ToList();
                if (_list == null)
                    _list = DB.Entities.TrainingsPlaces.ToList();
                return _list;
            }
        }

        /// <summary>
        /// список активных объектов
        /// </summary>
        public List<TrainingsPlaces> TrainingsPlacesActiveList
        {
            get
            {
                var result = new List<TrainingsPlaces>();
                if (TrainingsPlacesList.Count < 1) return result;
                result.AddRange(TrainingsPlacesList.Where(item => item.IsActive));
                return result;
            }
        }

        /// <summary>
        /// список для дроп-дауна со значением "Выбрать всех"
        /// </summary>
        public List<TrainingsPlaces> DropDownList
        {
            get
            {
                var result = new List<TrainingsPlaces>();
                var selectAllItem = new TrainingsPlaces {NameRu = "Выбрать всех", NameEn = "Select All"};
                result.Add(selectAllItem);
                if (TrainingsPlacesActiveList.Count < 1) return result;
                result.AddRange(TrainingsPlacesActiveList.OrderBy(p => p.NameRu));
                return result;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TrainingsPlaces.Find(itemId);
        }

        /// <summary>
        /// получить список элементов из строки разделенной сепараторами
        /// </summary>
        /// <param name="placeStr"></param>
        /// <param name="separatorStr"></param>
        /// <returns></returns>
        public List<TrainingsPlaces> GetPlacesFromString(string placeStr, char separatorStr = ';')
        {
            var result = new List<TrainingsPlaces>();
            new TrainingsPlaces();
            string[] trainersArray = placeStr.Split(separatorStr);
            foreach (string item in trainersArray)
            {
                int placeId = GetIdByName(item.Trim());
                if (placeId <= 0) continue;
                var placeItem = (TrainingsPlaces) GetItemById(placeId);
                if (placeItem != null)
                {
                    result.Add(placeItem);
                }
            }
            return result;
        }

        /// <summary>
        /// получить список площадок курса
        /// </summary>
        /// <param name="course"></param>
        /// <returns></returns>
        public List<TrainingsPlaces> GetPlacesListByCourse(TrainingsCourses course)
        {
            var result = new List<TrainingsPlaces>();
            var bindingCol = new TrainingsCoursesPlacesCollection();
            if (bindingCol.TrainingsCoursesPlacesList.Count < 1) return result;
            foreach (TrainingsCoursesPlaces item in bindingCol.TrainingsCoursesPlacesList)
            {
                if (item.IdTrainingsCourse == course.IdTrainingsCourse)
                {
                    var place = (TrainingsPlaces) GetItemById(item.IdTrainingsPlace);
                    if (place != null)
                        result.Add(place);
                }
            }
            return result;
        }

        /// <summary>
        /// Возвращает список площадок, привязанных к курсу
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public List<TrainingsPlaces> GetPlacesListByCourseId(int courseId)
        {
            var coursesCol = new TrainingsCoursesCollection();
            var courseItem = (TrainingsCourses) coursesCol.GetItemById(courseId);
            return courseItem != null ? GetPlacesListByCourse(courseItem) : new List<TrainingsPlaces>();
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (TrainingsPlaces) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TrainingsPlaces;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.NameRu))
                object4Update.NameRu = newObject.NameRu;

            if (!string.IsNullOrEmpty(newObject.NameEn))
                object4Update.NameEn = newObject.NameEn;

            if (!string.IsNullOrEmpty(newObject.CommentsRu))
                object4Update.CommentsRu = newObject.CommentsRu;

            if (!string.IsNullOrEmpty(newObject.CommentsEn))
                object4Update.CommentsEn = newObject.CommentsEn;

            object4Update.IdTrainingsCenter = newObject.IdTrainingsCenter;
            object4Update.Capacity = newObject.Capacity;

            if (!string.IsNullOrEmpty(newObject.Address))
                object4Update.Address = newObject.Address;

            object4Update.IdTrainingsCity = newObject.IdTrainingsCity;

            if (!string.IsNullOrEmpty(newObject.AcceptanceFileName))
                object4Update.AcceptanceFileName = newObject.AcceptanceFileName;

            object4Update.IsActive = newObject.IsActive;

            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TrainingsPlacesList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TrainingsPlaces);
        }

        #endregion
    }
}